{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3768ec43",
   "metadata": {},
   "source": [
    "# Extension for Scikit-learn DBSCAN for spoken arabic digit dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b1b922d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from timeit import default_timer as timer\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import davies_bouldin_score\n",
    "from sklearn.datasets import fetch_openml\n",
    "from IPython.display import HTML\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be391256",
   "metadata": {},
   "source": [
    "### Download the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7e73dc65",
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = fetch_openml(name=\"spoken-arabic-digit\", return_X_y=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "246f819f",
   "metadata": {},
   "source": [
    "### Preprocessing\n",
    "Split the data into train and test sets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6fd95eeb",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33da61da",
   "metadata": {},
   "source": [
    "Normalize the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "454a341c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "scaler_x = MinMaxScaler()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "02a779e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler_x.fit(x_train)\n",
    "x_train = scaler_x.transform(x_train)\n",
    "x_test = scaler_x.transform(x_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe1d4fac",
   "metadata": {},
   "source": [
    "### Patch original Scikit-learn with Extension for Scikit-learn\n",
    "Extension for Scikit-learn (previously known as daal4py) contains drop-in replacement functionality for the stock Scikit-learn package. You can take advantage of the performance optimizations of Extension for Scikit-learn by adding just two lines of code before the usual Scikit-learn imports:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ef6938df",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Extension for Scikit-learn* enabled (https://github.com/uxlfoundation/scikit-learn-intelex)\n"
     ]
    }
   ],
   "source": [
    "from sklearnex import patch_sklearn\n",
    "\n",
    "patch_sklearn()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20c5ab48",
   "metadata": {},
   "source": [
    "Extension for Scikit-learn patching affects performance of specific Scikit-learn functionality. Refer to the [list of supported algorithms and parameters](https://uxlfoundation.github.io/scikit-learn-intelex/latest/algorithms.html) for details. In cases when unsupported parameters are used, the package fallbacks into original Scikit-learn. If the patching does not cover your scenarios, [submit an issue on GitHub](https://github.com/uxlfoundation/scikit-learn-intelex/issues)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f80273e7",
   "metadata": {},
   "source": [
    "Training of the DBSCAN algorithm with Extension for Scikit-learn for spoken arabic digit dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1ffc93c7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Extension for Scikit-learn time: 6.37 s'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.cluster import DBSCAN\n",
    "\n",
    "params = {\n",
    "    \"n_jobs\": -1,\n",
    "}\n",
    "start = timer()\n",
    "y_pred = DBSCAN(**params).fit_predict(x_train)\n",
    "train_patched = timer() - start\n",
    "f\"Extension for Scikit-learn time: {train_patched:.2f} s\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f10b51fc",
   "metadata": {},
   "source": [
    "Let's take a look at Davies-Bouldin score of the DBSCAN algorithm with Extension for Scikit-learn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d4295a26",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Extension for Scikit-learn Davies-Bouldin score: 0.8542652084275848'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "score_opt = davies_bouldin_score(x_train, y_pred)\n",
    "f\"Extension for Scikit-learn Davies-Bouldin score: {score_opt}\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbe6db0d",
   "metadata": {},
   "source": [
    "### Train the same algorithm with original Scikit-learn\n",
    "In order to cancel optimizations, we use *unpatch_sklearn* and reimport the class DBSCAN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6f64ba97",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearnex import unpatch_sklearn\n",
    "\n",
    "unpatch_sklearn()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f242c6da",
   "metadata": {},
   "source": [
    "Training of the DBSCAN algorithm with original Scikit-learn library for spoken arabic digit dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "67243849",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Original Scikit-learn time: 469.21 s'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.cluster import DBSCAN\n",
    "\n",
    "start = timer()\n",
    "y_pred = DBSCAN(**params).fit_predict(x_train)\n",
    "train_unpatched = timer() - start\n",
    "f\"Original Scikit-learn time: {train_unpatched:.2f} s\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c85a125c",
   "metadata": {},
   "source": [
    "Let's take a look Davies-Bouldin score of the DBSCAN algorithm with original Scikit-learn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "cd9e726c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Original Scikit-learn Davies-Bouldin score: 0.8542652084275848'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "score_original = davies_bouldin_score(x_train, y_pred)\n",
    "f\"Original Scikit-learn Davies-Bouldin score: {score_opt}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3639eef9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<h3>Compare Davies-Bouldin score of patched Scikit-learn and original</h3>Davies-Bouldin score of patched Scikit-learn: 0.8542652084275848 <br>Davies-Bouldin score of unpatched Scikit-learn: 0.8542652084275848 <br>Metrics ratio: 1.0 <br><h3>With Scikit-learn-intelex patching you can:</h3><ul><li>Use your Scikit-learn code for training and prediction with minimal changes (a couple of lines of code);</li><li>Get comparable model quality</li><li>Get a <strong>73.6x</strong> speedup.</li></ul>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "HTML(\n",
    "    f\"<h3>Compare Davies-Bouldin score of patched Scikit-learn and original</h3>\"\n",
    "    f\"Davies-Bouldin score of patched Scikit-learn: {score_opt} <br>\"\n",
    "    f\"Davies-Bouldin score of unpatched Scikit-learn: {score_original} <br>\"\n",
    "    f\"Metrics ratio: {score_opt/score_original} <br>\"\n",
    "    f\"<h3>With Scikit-learn-intelex patching you can:</h3>\"\n",
    "    f\"<ul>\"\n",
    "    f\"<li>Use your Scikit-learn code for training and prediction with minimal changes (a couple of lines of code);</li>\"\n",
    "    f\"<li>Get comparable model quality</li>\"\n",
    "    f\"<li>Get a <strong>{(train_unpatched/train_patched):.1f}x</strong> speedup.</li>\"\n",
    "    f\"</ul>\"\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
